package com.whut.util;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.*;

public class FileUtil {

    private static final Logger logger = Logger.getLogger(FileUtil.class);

    /**
     * 判断文件是否存在
     * @param path
     * @return boolean
     */
    public static boolean isExist(String path) {
        File file = new File(path);
        if (file.exists()) {
            return true;
        }
        return false;
    }
    /**
     * 新建目录
     * @param folderPath
     * @return boolean
     */
    public static int newFolder(String folderPath) {
        try {
            File myFilePath = new File(folderPath);
            if (myFilePath.exists()) {
                return 400;//错误的请求
            }
            if(!myFilePath.mkdirs()){
                return 500;//服务器内部错误
            }
        } catch (Exception e) {
            logger.info("新建目录操作出错 ");
            e.printStackTrace();
            return 500;
        }
        return 200;//ok
    }
    /**
     * 新建文件
     * @param filePathAndName
     *            String 文件路径及名称 如c:/fqf.txt
     * @param fileContent
     *            String 文件内容
     * @return boolean
     */
    public static int newFile(String filePathAndName, String fileContent) {
        try {
            File myFilePath = new File(filePathAndName);
            if (myFilePath.exists()) {
                return 400;//错误的请求
            }
            FileWriter resultFile = new FileWriter(myFilePath);
            PrintWriter myFile = new PrintWriter(resultFile);
            myFile.print(fileContent);
            resultFile.close();
        } catch (Exception e) {
            logger.info("新建文件操作出错 ");
            e.printStackTrace();
            return 500;//服务器内部错误
        }
        return 200;
    }
    public static int newFileByCover(String filePathAndName, String fileContent) {
        try {
            File myFilePath = new File(filePathAndName);
            FileWriter resultFile = new FileWriter(myFilePath);
            PrintWriter myFile = new PrintWriter(resultFile);
            myFile.print(fileContent);
            resultFile.close();
        } catch (Exception e) {
            logger.info("新建文件操作出错 ");
            e.printStackTrace();
            return 500;//服务器内部错误
        }
        return 200;
    }
    /**
     * 追加文件：使用FileWriter
     */
    public static int appendFile(String filePathAndName, String fileContent) {
        try {
            //打开一个写文件器，构造函数中的第二个参数true表示以追加形式写文件
            FileWriter writer = new FileWriter(filePathAndName, true);
            writer.write(fileContent);
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
            return 500;
        }
        return 200;
    }
    public static int renameFile(String oldFilePathAndName,String newName){
        int index = oldFilePathAndName.lastIndexOf("/");
        if(index!=-1)
        {
            String oldName = oldFilePathAndName.substring(index+1);
            String path = oldFilePathAndName.substring(0,index);
            if(!oldName.equals(newName)){
                File oldFile=new File(oldFilePathAndName);
                File newFile=new File(path+"/"+newName);
                if(!oldFile.exists()){
                    //旧文件不存在
                    return 201;
                }
                if(newFile.exists()) {
                    //新文件已存在
                    return 400;
                }
                else{
                    if(oldFile.renameTo(newFile)) {
                        return 200;
                    }else {
                        return 500;
                    }
                }
            }else{
                return 400;
            }
        }
        return 400;
    }
    /**
     * 删除文件
     *
     * @param filePathAndName
     *            String 文件路径及名称 如c:/fqf.txt
     * @return boolean
     */
    public static boolean delFile(String filePathAndName) {
        boolean result=true;
        try {
            java.io.File myDelFile = new java.io.File(filePathAndName);
            result&=myDelFile.delete();

        } catch (Exception e) {
            result=false;
            logger.info("删除文件操作出错");
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 删除文件夹里面的所有文件
     *
     * @param path
     *            String 文件夹路径 如 c:/fqf
     */
    public static boolean delAllFile(String path) {
        boolean result=true;
        File file = new File(path);
        if (!file.exists()) {
            return false;
        }
        if (!file.isDirectory()) {
            return false;
        }
        String[] tempList = file.list();
        File temp = null;
        for (int i = 0; i < tempList.length; i++) {
            if (path.endsWith(File.separator)) {
                temp = new File(path + tempList[i]);
            } else {
                temp = new File(path + File.separator + tempList[i]);
            }
            if (temp.isFile()) {
                result&=temp.delete();
            }
            if (temp.isDirectory()) {
                result&=delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
                result&=delFolder(path + "/" + tempList[i]);// 再删除空文件夹
            }
        }
        return result;
    }
    /**
     * 删除文件夹
     *
     * @param folderPath
     *            String 文件夹路径及名称 如c:/fqf
     * @return boolean
     */
    public static boolean delFolder(String folderPath) {
        boolean result =true;
        try {
            result&=delAllFile(folderPath); // 删除完里面所有内容
            java.io.File myFilePath = new java.io.File(folderPath);
            result&=myFilePath.delete(); // 删除空文件夹
        } catch (Exception e) {
            result=false;
            logger.info("删除文件夹操作出错 ");
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 复制单个文件
     *
     * @param oldPath
     *            String 原文件路径 如：c:/fqf.txt
     * @param newPath
     *            String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public static void copyFile(String oldPath, String newPath) {
        boolean result=true;
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { // 文件存在时
                InputStream inStream = new FileInputStream(oldPath); // 读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1024];
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; // 字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        } catch (Exception e) {
            logger.info("复制单个文件操作出错 ");
            e.printStackTrace();

        }

    }

    /**
     * 复制整个文件夹内容
     *
     * @param oldPath
     *            String 原文件路径 如：c:/fqf
     * @param newPath
     *            String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public static void copyFolder(String oldPath, String newPath) {
        try {
            (new File(newPath)).mkdirs(); // 如果文件夹不存在 则建立新文件夹
            File a = new File(oldPath);
            String[] file = a.list();
            File temp = null;
            for (int i = 0; i < file.length; i++) {
                if (oldPath.endsWith(File.separator)) {
                    temp = new File(oldPath + file[i]);
                } else {
                    temp = new File(oldPath + File.separator + file[i]);
                }

                if (temp.isFile()) {
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath
                            + "/" + (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ((len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if (temp.isDirectory()) {// 如果是子文件夹
                    copyFolder(oldPath + "/" + file[i], newPath + "/"
                            + file[i]);
                }
            }
        } catch (Exception e) {
            logger.info("复制整个文件夹内容操作出错 ");
            e.printStackTrace();

        }

    }
    /**
     * 移动文件到指定目录
     *
     * @param oldPath
     *            String 如：c:/fqf.txt
     * @param newPath
     *            String 如：d:/fqf.txt
     */
    public static void moveFile(String oldPath, String newPath) {
        copyFile(oldPath, newPath);
        delFile(oldPath);
    }
    /**
     * 移动文件
     * @param srcFileName 	源文件完整路径
     * @param destDirName 	目的目录完整路径
     * @return 文件移动成功返回true，否则返回false
     */
    public static boolean moveFileToFolder(String srcFileName, String destDirName) {

        File srcFile = new File(srcFileName);
        if(!srcFile.exists() || !srcFile.isFile())
            return false;

        File destDir = new File(destDirName);
        if (!destDir.exists())
            destDir.mkdirs();

        return srcFile.renameTo(new File(destDirName + File.separator + srcFile.getName()));
    }
    /**
     * 移动文件夹到指定目录
     *
     * @param oldPath
     *            String 如：c:/fqf
     * @param newPath
     *            String 如：d:/fqf
     */
    public static void moveFolder(String oldPath, String newPath) {
        copyFolder(oldPath, newPath);
        delFolder(oldPath);
    }
    public static JSONObject getDirectoryCatalog(String directory){
        //获取pathName的File对象
        File dirFile = new File(directory);
        //判断该文件或目录是否存在，不存在时在控制台输出提醒
        if (!dirFile.exists()) {
            logger.info("directory do not exit");
            return null;
        }
        //文件夹或者文件存在
        JSONObject jsonObject=new JSONObject();
        JSONArray jsonArray =new JSONArray();
        try {
            //如果是一个文件夹则递归遍历文件夹
            if (dirFile.isDirectory()) {
                String[] fileList = dirFile.list();
                for (int i = 0; i < fileList.length; i++) {
                    //遍历文件目录
                    File file = new File(dirFile.getPath(), fileList[i]);
                    if (file.isDirectory()) {
                        jsonArray.put(getDirectoryCatalog(file.getAbsolutePath()));
                    } else {
                        JSONObject fileObject=new JSONObject();
                        fileObject.put("name",fileList[i]);
                        jsonArray.put(fileObject);
                    }
                }
                jsonObject.put("name",dirFile.getName());
                jsonObject.put("open",true);
                jsonObject.put("children",jsonArray);
            }
        }catch(JSONException e){
            e.printStackTrace();
        }

        return jsonObject;
    }
    public static String[] getDirectoryList(String directory)
    {
        File dirFile = new File(directory);
        if (!dirFile.exists()) {
            logger.info("directory do not exit");
            return null;
        }
        if (dirFile.isDirectory()) {
            return dirFile.list();
        }
        return null;
    }
    /**
     * 以行为单位读取文件，常用于读面向行的格式化文件
     */
    public static String readFileByLines(String filePath) {
        File file = new File(filePath);
        BufferedReader reader = null;
        String text="";
        try {
            reader = new BufferedReader(new FileReader(file));
            String tempString = null;
            // 一次读入一行，直到读入null为文件结束
            while ((tempString = reader.readLine()) != null) {
                text+=(tempString+'\n');
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e1) {
                }
            }
        }
        return text;
    }

    public static void main(String[] args) {
//        newFolder("C:\\Users\\Administrator\\Desktop\\test\\test");
//        newFile("C:\\Users\\Administrator\\Desktop\\test\\test\\text1.txt","hello");
//        delFile("C:\\Users\\Administrator\\Desktop\\test2\\test.txt");
//        delAllFile("C:\\Users\\Administrator\\Desktop\\test");
//        delFolder("C:\\Users\\Administrator\\Desktop\\test");
//        copyFile("C:\\Users\\Administrator\\Desktop\\soapui.log","C:\\Users\\Administrator\\Desktop\\soapui.txt");
//        copyFolder("C:\\Users\\Administrator\\Desktop\\虚拟机配置","C:\\Users\\Administrator\\Desktop\\test");
//        moveFile("C:\\Users\\Administrator\\Desktop\\会议摘要.txt","C:\\Users\\Administrator\\Desktop\\test.txt");
//        moveFileToFolder("C:\\Users\\Administrator\\Desktop\\test.txt","C:\\Users\\Administrator\\Desktop\\test");
//        moveFolder("C:\\Users\\Administrator\\Desktop\\test","C:\\Users\\Administrator\\Desktop\\test2");
//        JSONObject object = getDirectoryCatalog("C:\\Users\\Administrator\\Desktop\\yangyun");
//        System.out.println(object);
//        System.out.println(readFileByLines("C:\\Users\\Administrator\\Desktop\\yangyun\\run.py"));

    }
}
